﻿using System;
using System.Collections;
using System.Data;
using System.Diagnostics;
using System.IO;

namespace Jayrock.Json.Conversion.Converters
{
    internal sealed class DataTableV1Importer : ImporterBase
    {
        public DataTableV1Importer() : base(typeof(DataTable)) { }
        protected override object ImportFromString(ImportContext context, JsonReader reader)
        {
            Debug.Assert(context != null);
            Debug.Assert(reader != null);

            return ReadReturning(reader, Import(context, new JsonTextReader(new StringReader(reader.Text))));
        }

        protected override object ImportFromObject(ImportContext context, JsonReader reader)
        {
            Debug.Assert(context != null);
            Debug.Assert(reader != null);

            JsonObject obj = new JsonObject();
            obj.Import(reader);
            DataTable rslt = new DataTable();
            if (obj.Contains("tablename"))
            {
                rslt.TableName = obj["tablename"].ToString();
            }

            if (obj.Contains("columns"))
            {
                JsonArray cols = obj["columns"] as JsonArray;
                for (int i = 0; i < cols.Length; i++)
                {
                    rslt.Columns.Add(Convert.ToString(cols[i]));
                }
            }

            if (obj.Contains("rows"))
            {
                JsonArray rows = obj["rows"] as JsonArray;
                if (rows != null)
                {
                    foreach (JsonObject row in rows)
                    {
                        DataRow drow = rslt.NewRow();
                        foreach (object col in row.Names)
                        {
                            drow[col.ToString()] = (row as IDictionary)[col];
                        }
                        rslt.Rows.Add(drow);
                    }
                }
            }

            return rslt;
        }
    }
}
